package com.team6.stickynote.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import com.team6.stickynote.App;
import com.team6.stickynote.R;
import com.team6.stickynote.base.BaseActivity;
import com.team6.stickynote.beans.StickyNoteBean;
import com.team6.stickynote.databinding.ActivityEditBinding;
import com.team6.stickynote.databinding.ActivityMainBinding;
import com.team6.stickynote.sql.DBAdapter;
import com.team6.stickynote.util.ToastUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

public class EditActivity extends BaseActivity {

    public static final String EXTRA_STICKY_NOTE_BEAN_ID = "extra_sticky_note_bean_id";

    private ActivityEditBinding binding;

    StickyNoteBean stickyNoteBean;

    @Override
    protected void initBinding() {
        binding = ActivityEditBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initData();

        binding.btnSave.setOnClickListener(view -> {
            save();
        });
    }

    private void initData() {
        Intent intent = getIntent();

        long id = intent.getLongExtra(EXTRA_STICKY_NOTE_BEAN_ID, 0);
        stickyNoteBean = App.database.queryOneData(id);
        if (stickyNoteBean != null) {
            binding.etTitle.setText(stickyNoteBean.getTitle());
            binding.etContent.setText(stickyNoteBean.getText());
        }
    }

    private void save() {
        if (stickyNoteBean != null) {
            String title = binding.etTitle.getText().toString();
            String content = binding.etContent.getText().toString();
            if (TextUtils.isEmpty(title)) {
                ToastUtil.toast( "标题不能为空！");
                return;
            }

            stickyNoteBean.setTitle(title);
            stickyNoteBean.setText(content);
            long id=stickyNoteBean.getId();
            long rowId = App.database.updateOneData(id,stickyNoteBean);
            if (rowId != -1) {
                ToastUtil.toast("修改成功！");
                this.finish();
            } else {
                ToastUtil.toast("修改失败！");
            }

        } else {
            ToastUtil.toast("当前编辑的标签不存在！");
        }

    }


}